using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace BlimpControlPanel
{
   public partial class SaveFileDialogKLM : Form
   {
      ArrayList latLongAltArray;

       /// <summary>
       /// 
       /// </summary>
      public SaveFileDialogKLM()
      {
         InitializeComponent();
         latLongAltArray = new ArrayList();
      }

      private void btnBrowseNMEAData_Click(object sender, EventArgs e)
      {
          OpenFileDialog ofd = new OpenFileDialog();

          ofd.DefaultExt = "*.txt";
          ofd.Filter = "Text (*.txt)|*.txt|All Files (*.*)|*.*";
          ofd.AddExtension = true;

          DialogResult dr = ofd.ShowDialog();

          if (dr == DialogResult.OK)
              tbNMEAFilename.Text = ofd.FileName;
      }

      private void btnBrowseKmlFile_Click(object sender, EventArgs e)
      {
          SaveFileDialog sfd = new SaveFileDialog();
          sfd.Filter = "KML File(*.kml)|*.kml|All Files (*.*)|*.*";
          sfd.FileName = "test.kml";

          if (sfd.ShowDialog(this) == DialogResult.OK)
              tbKMLFilename.Text = sfd.FileName;
      }

      private void btnConvert_Click(object sender, EventArgs e)
      {
          if (!File.Exists(tbNMEAFilename.Text))
              return;

          StreamReader sr = new StreamReader(new FileStream(tbNMEAFilename.Text, FileMode.Open));

          string dataLine = "";
          bool dataValid = false;

          while (!sr.EndOfStream)
          {
              dataLine = sr.ReadLine();

              if (dataValid)
                  ParseDataLine(dataLine.Split(','));
              else if (dataLine.StartsWith("$GPGSA"))
                  dataValid = ParseGPGSAMessage(dataLine, dataValid);
          }

          sr.Close();

          xmlParsing parser = new xmlParsing();
          parser.saveKMLData(tbKMLFilename.Text, tbPathname.Text, latLongAltArray, new ProgressBar(), false);
          MessageBox.Show(this, "Conversion Complete", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);

      }

      private bool ParseGPGSAMessage(string dataLine, bool dataValid)
      {
          string[] data = dataLine.Split(',');

          if (data.Length == 18)
          {
              if (data[2] == "2" || data[2] == "3")
                  return true;
              else
                  return false;
          }

          return dataValid;
      }

      private void ParseDataLine(string [] dataLine)
      {
          //if (dataLine[0] == "$GPRMC" && dataLine.Length == 13)
          //{
          //    if(dataLine[2] != "A")
          //        return;

          //    Utilities utils = new Utilities();
          //    double [] data = utils.ConverStringsToData(dataLine);

          //    latLongAltArray.Add(utils.FormatDate(dataLine[9]) + ", " + utils.FormatTime(dataLine[1]) + ", " +
          //        ConvertLongitude(dataLine[5]) + ", " + ConvertLatitude(dataLine[3]) + ", " + 1000);
          //}
          if (dataLine[0] == "$GPGGA" && dataLine.Length == 15 && CheckSumValid(dataLine))
          {
              Utilities utils = new Utilities();

              latLongAltArray.Add(utils.FormatDate(dataLine[9]) + ", " + utils.FormatTime(dataLine[1]) + ", " +
                  utils.ConvertLongitude(dataLine[4], dataLine[5]) + ", " + utils.ConvertLatitude(dataLine[2], dataLine[3]) + ", " +
                  utils.ConvertMetersToFeet(dataLine[9]));
          }
      }

      public bool CheckSumValid(string[] dataLine)
      {
          byte CS = 0;
          string sentCS = "";

          foreach (string data in dataLine)
          {
              for (int i = 0; i < data.ToCharArray().Length; i++)
              {
                  if (data.ToCharArray()[i] == '$')
                      continue;
                  else if (data.ToCharArray()[i] == '*')
                  {
                      i++;

                      for (; i < data.Length; i++)
                          sentCS += data.ToCharArray()[i].ToString();

                      break;
                  }

                  CS ^= (byte)data.ToCharArray()[i];
              }
          }

          int sentCSInt = 0;

          bool parseOK = int.TryParse(sentCS, System.Globalization.NumberStyles.HexNumber, null, out sentCSInt);

          System.Diagnostics.Debug.WriteLine("CS: " + CS.ToString("X02") + " SentCS: " + sentCSInt.ToString("X02"));

          bool valid = (CS == sentCSInt);
          return valid && parseOK;
      }
   }
}